import os
import shutil
import random

# 定义源 txt 文件和目标文件夹路径
txt_file = 'image_paths.txt'  # 存放图片绝对路径的 txt 文件
destination_folder = 'target_folder'  # 目标文件夹，图片将被保存到这里
get_thread = 0.1

# 确保目标文件夹存在，如果不存在则创建
if not os.path.exists(destination_folder):
    os.makedirs(destination_folder)

# 读取 txt 文件中的图片路径
with open(txt_file, 'r') as f:
    # 读取所有图片路径，并去掉每行的换行符
    image_paths = [line.strip() for line in f.readlines()]

# 随机抽取 get_thread 的图片路径
num_images_to_select = max(1, int(len(image_paths) * get_thread))  # 保证至少抽取一张图片
selected_image_paths = random.sample(image_paths, num_images_to_select)

# 复制抽取的图片到目标文件夹
for image_path in selected_image_paths:
    if os.path.exists(image_path):
        # 获取图片文件的文件名（不带路径）
        image_name = os.path.basename(image_path)

        # 拼接目标文件夹路径和图片文件名
        destination_path = os.path.join(destination_folder, image_name)

        # 复制图片到目标文件夹
        shutil.copy(image_path, destination_path)
        print(f"已将 {image_name} 复制到 {destination_folder}")
    else:
        print(f"警告：文件 {image_path} 不存在，跳过复制。")
